import Interface
import Like
import Search
import Play
import Data
import Download

import tkinter as tk
import requests
import random

checkUrl = Data.baseUrl + "/check/music?id="
getUrl = Data.baseUrl + "/song/url?id="


def freshScro(type):
    # 刷新滚动条
    if type == "like":
        # 将滚动按钮绑定在Like板块的Canvas上
        Like.likeCanvas.bind_all("<MouseWheel>", lambda event: Like.likeCanvas.yview_scroll(-1 * (int(event.delta / 120)), "units"))
        Like.likeCanvas.configure(yscrollcommand=Like.likeScro.set, scrollregion=Like.likeCanvas.bbox("all"))
        Like.likeScro.config(command=Like.likeCanvas.yview)
    elif type == "search":
        # 将滚动按钮绑定在Search的Canvas上
        Search.searchCanvas.bind_all("<MouseWheel>", lambda event: Search.searchCanvas.yview_scroll(-1 * (int(event.delta / 120)), "units"))
        Search.searchCanvas.configure(yscrollcommand=Search.searchScro.set, scrollregion=Search.searchCanvas.bbox("all"))
        Search.searchScro.config(command=Search.searchCanvas.yview)
    elif type == "play":
        # 将滚动按钮绑定在Like板块的Canvas上
        Play.playCanvas.bind_all("<MouseWheel>", lambda event: Play.playCanvas.yview_scroll(-1 * (int(event.delta / 120)), "units"))
        Play.playCanvas.configure(yscrollcommand=Play.playScro.set, scrollregion=Play.playCanvas.bbox("all"))
        Play.playScro.config(command=Play.playCanvas.yview)


def display(type, list):
    # 确保画布内容为空
    if type == "like":
        Like.likeCanvas.delete(tk.ALL)
    elif type == "search":
        Search.searchCanvas.delete(tk.ALL)

    # 刷新滚动条
    freshScro(type)

    # 生成容器
    if type == "like":
        frame = tk.Frame(Like.mainLikeFrame)
        frame.pack(side='top')
        # 将Frame添加至Canvas上
        Like.likeCanvas.create_window(0, 0, window=frame, anchor="w")
    elif type == "search":
        frame = tk.Frame(Search.mainSearchFrame)
        frame.pack(side='top')
        # 将Frame添加至Canvas上
        Search.searchCanvas.create_window(0, 0, window=frame, anchor="w")

    # 定义frame列表
    frame = []
    i = 0
    n = 0

    # 没有符合条件的结果
    if len(list) == 0:
        if type == "like":
            # 生成容器
            frame.append(tk.Frame(Like.likeCanvas))
            frame[i].pack(side='left', anchor="w", fill="both")
            # 将Frame添加至Canvas上
            Like.likeCanvas.create_window(0, 3 * 30 * i + 100, window=frame[i], anchor="w")
        elif type == "search":
            # 生成容器
            frame.append(tk.Frame(Search.searchCanvas))
            frame[i].pack(side='left', anchor="w", fill="both")
            # 将Frame添加至Canvas上
            Search.searchCanvas.create_window(0, 3 * 30 * i + 100, window=frame[i], anchor="w")

        if type == "like":
            tk.Label(frame[i], text="快去添加喜欢的歌曲", fg=Interface.color[n]).pack(side='left', anchor="w", fill="both")
        elif type == "search":
            tk.Label(frame[i], text="未查询到结果", fg=Interface.color[n], font=Interface.font).pack(side='left', anchor="w", fill="both")

    for song in list:
        # 生成随机数，如果随机数和上一轮重复，则另外生成
        m = n
        while m == n:
            n = random.randint(0, len(Interface.color) - 1)

        if type == "like":
            # 生成容器
            frame.append(tk.Frame(Like.likeCanvas))
            frame[i].pack(side='left', anchor="w", fill="both")
            # 将Frame添加至Canvas上
            Like.likeCanvas.create_window(0, 3 * 30 * i + 100, window=frame[i], anchor="w")
        elif type == "search":
            # 生成容器
            frame.append(tk.Frame(Search.searchCanvas))
            frame[i].pack(side='left', anchor="w", fill="both")
            # 将Frame添加至Canvas上
            Search.searchCanvas.create_window(0, 3 * 30 * i + 100, window=frame[i], anchor="w")

        # 本地文件检测
        try:
            title = Data.checkLocalFile(song)
        except FileNotFoundError:
            title = None
        # vip检测
        headers = {"Accept": "application/vnd.github.v3+json"}
        checkIdUrl = checkUrl + str(song.get("id"))
        data = requests.get(checkIdUrl, headers=headers)
        checkVIP = data.json()
        # 试听检测
        getIdUrl = getUrl + str(song.get("id"))
        data = requests.get(getIdUrl, headers=headers)
        checkAudition = data.json()

        if title == song.get("name"):
            tk.Label(frame[i], text="歌曲名：" + song.get("name") + "  Local", fg=Interface.color[n]).pack(side='top', anchor="w")
        else:
            if song.get("name") and checkVIP.get("success"):
                if checkAudition.get("data")[0].get("time") > 60000 and\
                        checkAudition.get("data")[0].get("freeTrialPrivilege").get("resConsumable") is False:
                    tk.Label(frame[i], text="歌曲名：" + song.get("name"), fg=Interface.color[n]).pack(side='top', anchor="w")
                else:
                    tk.Label(frame[i], text="歌曲名：" + song.get("name") + "   试听", fg=Interface.color[n]).pack(side='top', anchor="w")
            else:
                tk.Label(frame[i], text="歌曲名：" + song.get("name") + "  VIP", fg=Interface.color[n]).pack(side='top', anchor="w")

        artist_list = []
        for artist in song["artists"]:
            if artist.get("name"):
                artist_list.append(artist.get("name"))
        tk.Label(frame[i], text="音乐家：" + "   ".join(artist_list), fg=Interface.color[n]).pack(side='top', anchor="w")
        if song.get("album").get("name"):
            tk.Label(frame[i], text="专辑：" + song.get("album").get("name"), fg=Interface.color[n]).pack(side='top', anchor="w")

        # 生成容器
        operateFrame = tk.Frame(frame[i])
        operateFrame.pack(side='left')

        if type == "like":
            if title == song.get("name"):
                tk.Button(operateFrame, text="加入播放队列", fg=Interface.color[n], command=lambda item=song: Play.addPlayQueue(item)).pack(side='left', anchor="w")
            else:
                if checkVIP.get("success"):
                    if checkAudition.get("data")[0].get("freeTrialPrivilege").get("resConsumable") is False:
                        tk.Button(operateFrame, text="加入播放队列", fg=Interface.color[n], command=lambda item=song: Play.addPlayQueue(item)).pack(side='left', anchor="w")
                    else:
                        tk.Button(operateFrame, text="加入播放队列（试听）", fg=Interface.color[n], command=lambda item=song: Play.addPlayQueue(item)).pack(side='left', anchor="w")
                    tk.Button(operateFrame, text="下载", fg=Interface.color[n], command=lambda item=song: Download.download(item)).pack(side='left', anchor="w")
                else:
                    tk.Button(operateFrame, text="加入播放队列", fg=Interface.color[n], state=tk.DISABLED, command=lambda item=song: Play.addPlayQueue(item)).pack(side='left', anchor="w")
                    tk.Button(operateFrame, text="下载", fg=Interface.color[n], state=tk.DISABLED, command=lambda item=song: Download.download(item)).pack(side='left', anchor="w")
            tk.Button(operateFrame, text="取消喜欢", fg=Interface.color[n], command=lambda likeSong=song: Like.delete(likeSong)).pack(side='left', anchor="w")
        elif type == "search":
            if title == song.get("name"):
                tk.Button(operateFrame, text="加入播放队列", fg=Interface.color[n], command=lambda item=song: Play.addPlayQueue(item)).pack(side='left', anchor="w")
                tk.Button(operateFrame, text="下一首", fg=Interface.color[n], command=lambda item=song: Play.nextPlay(item)).pack(side='left', anchor="w")
            else:
                if checkVIP.get("success"):
                    if checkAudition.get("data")[0].get("freeTrialPrivilege").get("resConsumable") is False:
                        tk.Button(operateFrame, text="加入播放队列", fg=Interface.color[n], command=lambda item=song: Play.addPlayQueue(item)).pack(side='left', anchor="w")
                    else:
                        tk.Button(operateFrame, text="加入播放队列(试听)", fg=Interface.color[n], command=lambda item=song: Play.addPlayQueue(item)).pack(side='left', anchor="w")
                    tk.Button(operateFrame, text="下载", fg=Interface.color[n], command=lambda item=song: Download.download(item)).pack(side='left', anchor="w")
                else:
                    tk.Button(operateFrame, text="加入播放队列", fg=Interface.color[n], state=tk.DISABLED, command=lambda item=song: Play.addPlayQueue(item)).pack(side='left', anchor="w")
                    tk.Button(operateFrame, text="下载", fg=Interface.color[n], state=tk.DISABLED, command=lambda item=song: Download.download(item)).pack(side='left', anchor="w")
            tk.Button(operateFrame, text="喜欢", fg=Interface.color[n], command=lambda likeSong=song: Like.add(likeSong)).pack(side='left', anchor="w")

        # 更新Frame大小，不然没有滚动效果
        frame[i].update()
        i += 1
